import React, { useEffect, useState } from "react";
import { Button, Table, message, Popconfirm, DatePicker, Tag } from "antd";
import {
  listReturnApplications,
  createReturnApplication,
  updateReturnApplicationStatus,
  listProducts,
  listUsers,
} from "../../api/ckgl";
import ReturnApplicationModal from "./componets/ReturnApplicationModal";

const ListReturnApplications = () => {
  const [returnApplicationList, setReturnApplicationList] = useState<any[]>([]);
  const [totalReturnApplications, setTotalReturnApplications] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);
  const [isReturnApplicationModalVisible, setIsReturnApplicationModalVisible] =
    useState(false);
  const [currentReturnApplication, setCurrentReturnApplication] =
    useState<any>(null);
  const [productList, setProductList] = useState<any[]>([]);
  const [list, setList] = useState<any[]>([]);

  const columns = [
    {
      title: "ID",
      dataIndex: "application_id",
      key: "application_id",
    },
    // {
    //   title: "物品ID",
    //   dataIndex: "product_id",
    //   key: "product_id",
    // },
    {
      title: "物品",
      dataIndex: "product_id",
      key: "product_id",
      render: (product_id: number) => {
        const product = productList.find((p) => p.id === product_id);
        return product ? product.product_name : "";
      },
    },
    // {
    //   title: "归还人id",
    //   dataIndex: "applicant_id",
    //   key: "applicant_id",
    // },
    {
      title: "归还人id",
      dataIndex: "applicant_id",
      key: "applicant_id",
      render: (applicant_id: number) => {
        const user = list.find((u) => u.user_id === applicant_id);
        return user ? user.username : "";
      },
    },
    {
      title: "归还数量",
      dataIndex: "quantity",
      key: "quantity",
    },
    {
      title: "状态",
      dataIndex: "return_status",
      key: "return_status",
      render: (return_status: number) => {
        return ["", "待归还", "审核中", "已归还"][return_status];
      },
    },
    {
      title: "操作",
      dataIndex: "id",
      key: "id",
      render: (_: any, record: any) => (
        <>
          <Button
            onClick={() => {
              setCurrentReturnApplication(record);
              setIsReturnApplicationModalVisible(true);
            }}
          >
            更新状态
          </Button>
        </>
      ),
    },
  ];

  const getListReturnApplications = (page: number) => {
    listReturnApplications({
      paginator: {
        page: page,
        size: pageSize,
      },
    })
      .then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        const { return_application, total } = res.data;
        setReturnApplicationList(return_application);
        setTotalReturnApplications(total);
      })
      .catch(() => {
        const mockReturnApplications = [
          {
            application_id: 12346,
            product_id: 1,
            applicant_id: 1,
            quantity: 3,
            return_status: 2, // 1-待归还,2-审核中,3-已归还
          },
          {
            application_id: 12347,
            product_id: 3,
            applicant_id: 2,
            quantity: 8,
            return_status: 3, // 1-待归还,2-审核中,3-已归还
          },
          {
            application_id: 12348,
            product_id: 2,
            applicant_id: 3,
            quantity: 2,
            return_status: 1, // 1-待归还,2-审核中,3-已归还
          },

          // Add more mock data as needed
        ];
        setReturnApplicationList(mockReturnApplications);
        setTotalReturnApplications(mockReturnApplications.length);
      });
  };

  const reset = (page: number) => {
    getListReturnApplications(page);
  };

  const handleReturnApplicationModalOk = async (values: any) => {
    message.success("操作成功");
    if (currentReturnApplication) {
      // 更新
      let msg = "更新成功";
      await updateReturnApplicationStatus({
        ...currentReturnApplication,
        ...values,
      }).then((res: any) => {
        // if (res?.code !== 0) {
        //   message.error(res.msg);
        //   return;
        // }
        message.success(msg);
      });
    } else {
      // 添加
      let msg = "添加成功";
      await createReturnApplication({
        ...values,
      }).then((res: any) => {
        // if (res?.code !== 0) {
        //   message.error(res.msg);
        //   return;
        // }
        message.success(msg);
      });
    }
    // 更新当前页
    reset(currentPage);
    setIsReturnApplicationModalVisible(false);
  };

  useEffect(() => {
    getListReturnApplications(currentPage);
  }, [currentPage]);

  useEffect(() => {
    getListProducts();
    getListUsers();
  }, []);

  const getListProducts = () => {
    // 调用 listProducts API，并处理响应
    listProducts({
      page: 1,
      size: 200,
    })
      .then((res) => {
        // if (res?.code !== 0) {
        //   message.error(res.msg);
        //   return;
        // }
        // const {products, total} = res.data
        // setProductList(products);
        // setTotalProducts(total);
      })
      .catch(() => {
        // 用于演示目的，使用模拟数据
        const mockProducts = [
          {
            id: 1,
            product_name: "Product A",
            inventory: 100,
            reminder_threshold: 10,
          },
          {
            id: 2,
            product_name: "Product B",
            inventory: 50,
            reminder_threshold: 5,
          },
          // 添加更多的模拟产品
        ];

        setProductList(mockProducts);
      });
  };

  const getListUsers = () => {
    listUsers({
      page: 1,
      size: 200,
    })
      .then((res: any) => {
        console.log(res);
        //   if (res?.code !== 0) {
        //     message.error(res.msg);
        //     return;
        //   }
        //   // admin(系统管理员)，purchaser（采购人员），m-admin（物资管理员），picker（领物），visitor（游客）
        //   const { users, total } = res.data;
        //   setList(users);
        //   setTotal(total);
      })
      .finally(() => {
        const mockUsers: any[] = [
          {
            user_id: 1,
            username: "john_doe",
            email: "john@example.com",
            roles: [{ id: 1, role_name: "系统管理员" }],
            create_time: "2022-01-01T00:00:00Z",
          },
          {
            user_id: 2,
            username: "jane_doe",
            email: "jane@example.com",
            roles: [{ id: 2, role_name: "采购人员" }],
            create_time: "2022-01-02T00:00:00Z",
          },
          {
            user_id: 3,
            username: "jane_doe3",
            email: "jane@example.com",
            roles: [{ id: 3, role_name: "物资管理员" }],
            create_time: "2022-01-02T00:00:00Z",
          },
          // Add more mock users as needed
        ];

        setList(mockUsers);
      });
  };

  return (
    <div>
      <Button
        style={{ marginTop: "7px", marginLeft: "10px", float: "right" }}
        onClick={() => {
          setIsReturnApplicationModalVisible(true);
          setCurrentReturnApplication(null);
        }}
        size="large"
        type="primary"
      >
        创建归还申请
      </Button>
      <Table
        dataSource={returnApplicationList}
        columns={columns}
        rowKey="application_id"
        pagination={{
          pageSize,
          defaultCurrent: 1,
          onChange: setCurrentPage,
          total: totalReturnApplications,
        }}
      />
      <ReturnApplicationModal
        users={list}
        productList={productList}
        title={currentReturnApplication ? "更改归还申请状态" : "创建归还申请"}
        visible={isReturnApplicationModalVisible}
        onCancel={() => setIsReturnApplicationModalVisible(false)}
        onOk={handleReturnApplicationModalOk}
        defaultValue={currentReturnApplication || {}}
      />
    </div>
  );
};

export default ListReturnApplications;
